package com.witframework.components;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.witframework.core.persistence.IBaseJdbcDao;
import com.witframework.meta.MetaEntityField;
import com.witframework.web.mvc.Controller;
import com.witframework.web.mvc.WebContext;

@Component
public class AutoTableController implements Controller{
	

	public String executor(WebContext webContext) {
		String items=webContext.getContextParameterAndsetAttribute("items");
		
		String page=webContext.getContextParameterAndsetAttribute("page");
		String tableid=webContext.getContextParameterAndsetAttribute("tableId");		
		String data=webContext.getContextParameterAndsetAttribute("data");		
		String columns=webContext.getContextParameterAndsetAttribute("columns");		
		String datatype=webContext.getContextParameterAndsetAttribute("datatype");		
		try {
			data=java.net.URLDecoder.decode(data,"utf-8");			
		} catch (Exception e) {			
		}
		
		List dataList=null;
		List<CustomSelectEcProperty> viewPropertyList=new ArrayList<CustomSelectEcProperty>();
		
		if(datatype==null||datatype.equalsIgnoreCase("table")||datatype.equalsIgnoreCase("sql")){
			IBaseJdbcDao dao=(IBaseJdbcDao)com.witframework.core.BeanFactory.getBean("baseJdbcDao");			
			StringBuffer query=new StringBuffer();
			if(datatype==null||datatype.equalsIgnoreCase("table")){
				query.append("select "+columns+" from "+data);
				for(String property:columns.split(",")){
					query.insert(query.indexOf(property)+property.length()," "+property);
				}
			}else{
				query.append(data);
			}			
			dataList=dao.pageQuery(webContext.getPageSortModel(tableid), query.toString());				
			
		}else{
			webContext.renderHtml("不支持的数据源类型："+datatype);
		}		
		webContext.setAttribute(items, dataList);//待选的数据集		
		return page;
	}
	private String getDisplayName(String name, List<MetaEntityField> fields){
		for(MetaEntityField f:fields){
			if(f.getName().equals(name))
				return f.getDisplayName();
		}
		return name;
	}
	private String getDisplayFromTitles(String name, String titles){
		for(String p:titles.split(",")){
			String[] map=p.split(":");
			if(map[0].equalsIgnoreCase(name))
				return map[1];
		}
		return name;
	}	
}
